// 源插件
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DateDiff, DateStamp, FormatnumberZero, Mover, NumberDivide } from '@/function.js';
// 视图插件
import {
  AutoComplete,
  Card,
  Col,
  Form,
  Input,
  message,
  Row,
  Icon,
  Button,
  notification,
  Modal,
  Select,
} from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';

// 外部组件
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import KlineEcharts from '@/components/KlineEcharts/KlineEcharts';
import HeaderSearch from '@/components/HeaderSearch';
import $ from 'jquery';
import ReactKline from 'react-kline-pro';
import styles from '../../../components/GlobalHeader/index.less';
// css OR less预编译器

// 图片

const { Option } = AutoComplete;
const { Search } = Input;

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ ed, loading }) => ({
  ed,
  loading: loading.models.edRule,
}))
@Form.create()
class NewTwoEDStock extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    symbolList: [],
    date: '',
    symbol: '',
    Visible: false,
  };

  codeUpdate(code) {
    const that = this;
    const { dispatch } = this.props;
    const { date } = this.state;
    $.ajax({
      type: 'GET',
      url: `http://fss.91stock.net/fss/Kline/GetStockInfo?code=${code}`,
      contentType: 'application/x-www-form-urlencoded;charset=utf-8',
      dataType: 'json',
      async: true,
      success(data) {
        if (data.myCode !== null) {
          dispatch({
            type: 'ed/AddStock',
            payload: data.myCode,
            callback: res => {
              dispatch({
                type: 'ed/GetStockList',
                payload: date,
              });
            },
          });
        } else {
          message.error('暂无该股票信息');
        }
      },
      error(e) {
        console.log(e);
      },
    });
  }

  renderOption(item) {
    return (
      <Option key={item.code} label={item.code}>
        {`${item.market}  ${item.code}  ${item.name}`}
      </Option>
    );
  }

  deleteSymbol(code) {
    const that = this;
    const key = `open${Date.now()}`;
    const { dispatch } = that.props;
    const { date } = that.state;
    const btn = (
      <Button
        type="primary"
        size="small"
        onClick={() => {
          notification.close(key);
          dispatch({
            type: 'ed/DeleteStock',
            payload: code,
            callback: res => {
              dispatch({
                type: 'ed/GetStockList',
                payload: date,
              });
            },
          });
        }}
      >
        确定
      </Button>
    );
    notification.open({
      message: 'Notification Title',
      description: '是否删除',
      btn,
      key,
      onClose: close,
    });
  }

  klineModalOpen(value) {
    const that = this;
    that.setState({}, () => {
      $.ajax({
        type: 'GET',
        url: `http://fss.91stock.net/fss/Kline/GetStockInfo?code=${value}`,
        contentType: 'application/x-www-form-urlencoded;charset=utf-8',
        dataType: 'json',
        async: false,
        success(data) {
          if (data.myCode !== null) {
            that.setState({
              Visible: true,
              symbol: that.state.symbol === '' ? data.myCode : `${data.myCode}  ${Math.random()}`,
            });
          } else {
            message.error('暂无该股票信息');
          }
        },
        error(e) {
          console.log(e);
        },
      });
    });
  }

  klineModalClose() {
    this.setState({ Visible: false });
  }

  onRequestData(param, callback) {
    const that = this;
    $.ajax({
      type: 'GET',
      url: `http://192.168.84.68:8081/Kline/GetKline?code=${param.symbol}`,
      contentType: 'application/x-www-form-urlencoded;charset=utf-8',
      dataType: 'json',
      async: true,
      success(data) {
        if (data.code === 1) {
          const coordinates = [];
          coordinates[0] = data.coordinates[data.coordinates.length - 1];
          const dataCall = data.kline.data.item;
          callback({
            success: true,
            data: {
              lines: dataCall,
              monthCoordinates: data.monthCoordinates,
              caution: data.targetPrice,
              coordinates,
              symbol: data.kline.data.symbol,
            },
          });
        }
      },
      error(e) {
        console.log(e);
      },
    });
  }

  onSelectTime(date) {
    const { dispatch } = this.props;
    this.setState(
      {
        date,
      },
      () => {
        dispatch({
          type: 'ed/GetStockList',
          payload: date,
        });
      }
    );
  }

  render() {
    const {
      loading,
      dispatch,
      ed: { codeList, symbolList, selectDate },
    } = this.props;
    const { Visible } = this.state;
    const list = [];
    for (let i = 0; i < symbolList.length; i++) {
      list.push(
        <Col md={8} sm={24}>
          <Card
            hoverable
            bodyStyle={{ padding: '12px 4px' }}
            style={{
              width: '98%',
              height: '500px',
              marginTop: '3%',
              marginLeft: '1%',
              marginBottom: '3%',
            }}
          >
            <KlineEcharts mainId={`MAIN${i}`} name={symbolList[i].code} />
            <Icon
              type="fullscreen"
              style={{ fontSize: '16px', position: 'absolute', right: 15, top: 15 }}
              onClick={this.klineModalOpen.bind(this, symbolList[i].code)}
            />
            <Icon
              type="delete"
              style={{ fontSize: '16px', position: 'absolute', right: 45, top: 15 }}
              onClick={this.deleteSymbol.bind(this, symbolList[i].id)}
            />
            <div style={{ textAlign: 'center', marginLeft: '2%', fontWeight: '600' }}>
              {symbolList[i].code}
            </div>
          </Card>
        </Col>
      );
    }
    const selectList = [];
    for (let i = 0; i < selectDate.length; i++) {
      selectList.push(
        <Option key={!selectDate[i] ? ' ' : selectDate[i].substring(0, 10)}>
          {!selectDate[i] ? ' ' : selectDate[i].substring(0, 10)}
        </Option>
      );
    }
    return (
      <PageHeaderWrapper>
        <Card>
          <Row>
            <Col span={12}>
              <HeaderSearch
                className={`${styles.action} ${styles.search}`}
                placeholder={formatMessage({ id: '股票搜索' })}
                dataSource={codeList.map(this.renderOption.bind(this))}
                onChange={value => {
                  dispatch({
                    type: 'ed/SearchCode',
                    payload: value,
                  });
                }}
                onPressEnter={value => {
                  this.codeUpdate(value);
                }}
                style={{ paddingTop: 5, paddingLeft: 12 }}
              />
            </Col>
            <Col span={12} style={{ textAlign: 'right' }}>
              选择历史时间:
              <Select
                defaultValue="今日"
                style={{ width: 220, margin: ' 0px 30px 0px 12px' }}
                onChange={this.onSelectTime.bind(this)}
              >
                {selectList}
              </Select>
            </Col>
          </Row>

          <br />
          <div>{list}</div>
          <Modal
            width="90%"
            title="K线"
            footer=""
            visible={Visible}
            centered
            onOk={this.klineModalClose.bind(this)}
            onCancel={this.klineModalClose.bind(this)}
          >
            <ReactKline
              height={688}
              ranges={['1d']}
              symbol={this.state.symbol}
              symbolName={this.state.symbol}
              intervalTime={5000000000}
              depthWidth={100}
              onRequestData={this.onRequestData.bind(this)}
            />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { date } = this.state;
    dispatch({
      type: 'ed/GetStockList',
      payload: date,
    });
    dispatch({
      type: 'ed/GetFund2PlanStockDateList',
    });
  }

  componentWillUnmount() {}
}

export default NewTwoEDStock;
